package com.loyin.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;

import com.et.mvc.JsonView;
import com.et.mvc.JspView;
import com.et.mvc.View;
import com.loyin.model.DownloadUrl;
import com.loyin.model.UserInfo;
import com.loyin.model.UserInfoVo;
import com.loyin.model.WebSite;
import com.loyin.tool.AnalysisUrl;
import com.loyin.util.MD5;
import com.loyin.util.Page;

/**
 * 网站收录及分析
 * 
 * @author 刘声凤 2011-11-10
 */
public class WebSiteController extends ApplicationController
{
	private Logger log = Logger.getLogger(this.getClass());

	/**
	 * 查看列表
	 * 
	 * @param type
	 *            查看类型 0 最新增加
	 */
	public void list(int type)
	{
		WebSite website = new WebSite();
		UserInfoVo userinfovo = (UserInfoVo) session.getAttribute("user_session");
		StringBuffer sql = null;
		if(userinfovo.getRoleclass()==1)
			sql = new StringBuffer(" userid = ? ");
		else
			sql = new StringBuffer();
		try
		{
			switch (type)
			{
			case 0:
				break;
			case 1:
				break;
			case 2:
				break;
			case 3:
				break;
			default:
				break;
			}
			String pagenostr = request.getParameter("pageNo");
			String pagesizestr = request.getParameter("pageSize");
			if (pagenostr == null || "".equals(pagenostr.trim()))
			{
				pagenostr = "1";
			}
			if (pagesizestr == null || "".equals(pagesizestr.trim()))
			{
				pagesizestr = this.pagesize + "";
			}
			Page page = new Page(0, Integer.parseInt(pagenostr), Integer.parseInt(pagesizestr), null);
			List<Object> paramlist = new ArrayList<Object>();
			paramlist.add(userinfovo.id);
			String keyword = request.getParameter("keyword");
			request.setAttribute("keyword", keyword);
			if (keyword != null && !"".equals(keyword.trim()))
			{
				sql.append(" and keyword like ? ");
				paramlist.add("%" + keyword.trim() + "%");
			}
			String url = request.getParameter("url");
			request.setAttribute("url", url);
			if (url != null && !"".equals(url.trim()))
			{
				sql.append(" and url like ? ");
				paramlist.add("%" + url.trim() + "%");
			}
			String title = request.getParameter("title");
			request.setAttribute("title", title);
			if (title != null && !"".equals(title.trim()))
			{
				sql.append(" and title like ? ");
				paramlist.add("%" + title.trim() + "%");
			}
			List<WebSite> list = (List<WebSite>) website.findAll(website.getClass(), sql.toString(), paramlist.toArray(), " addtime desc ", page.getPageSize(), page.start);
			long count = website.count(website.getClass(), null, paramlist.toArray());
			page = new Page(count, Integer.parseInt(pagenostr), Integer.parseInt(pagesizestr), list);
			request.setAttribute("page", page);
		} catch (Exception e)
		{
			log.error("查看网站异常", e);
			request.setAttribute("stat", "E");
			request.setAttribute("msg", "访问出错");
		}
	}

	/** 新增需要收录的网站 */
	public void add(long id)
	{
		if (id != 0)
		{
			WebSite website = new WebSite();
			try
			{
				request.setAttribute("website", website.find(website.getClass(), id));
			} catch (Exception e)
			{
				log.error("导航到增加网页异常", e);
			}
		}
	}
	
	/** 新增需要收录的网站 */
	public void addoffline()
	{
		try
		{
			Map<String, Object> map = new HashMap<String, Object>();
			String usercode=request.getParameter("usercode");
			String pwd=request.getParameter("pwd");
			UserInfo user = new UserInfo();
			List<UserInfo> userlist = (List<UserInfo>) user.findBySql(user.getClass(),
					"select * from igs_userinfo where usercode=? and pwd=? ", new Object[]
					{ usercode , MD5.getMD5ofStr(pwd) });
			if (userlist == null || userlist.isEmpty() == true)
			{
				request.setAttribute("stat", "F");
				request.setAttribute("msg", "用户名或密码错误！");
			} else
			{
				UserInfoVo uservo = new UserInfoVo();
				BeanUtils.copyProperties(uservo, userlist.get(0));
				session.setAttribute("user_session", uservo);
				request.setAttribute("stat", "S");
			}
			
		} catch (Exception e)
		{
			log.error("导航到离线增加网页异常", e);
			request.setAttribute("stat", "F");
			request.setAttribute("msg_error", "访问出错，请联系系统管理员！");
		}
	}

	public View saveoffline(WebSite website)
	{
		Map<String, Object> map = new HashMap<String, Object>();
		try
		{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			website.addtime = sdf.format(new Date());
			website.save();
			
//			map.put("stat", "S");
//			map.put("msg", "保存成功，请继续添加");
//			map.put("id", website.id);
			request.setAttribute("stat", "S");
			request.setAttribute("msg", "保存成功，请继续添加");
			request.setAttribute("id", website.id);
		} catch (Exception e)
		{
			log.error("离线保存网址失败", e);
//			map.put("stat", "E");
//			map.put("msg", "保存网址失败");			
			request.setAttribute("stat", "E");
			request.setAttribute("msg", "保存网址失败");
		}
		JspView view = new JspView("/website/addoffline.jsp");
		return view;
		//return new JsonView(map);
	}
	
	public void update(long id)
	{
		if (id != 0)
		{
			WebSite website = new WebSite();
			try
			{
				request.setAttribute("website", website.find(website.getClass(), id));
//				String keyword=website.getKeyword();
//				if(keyword!=null)
//				{
//					String[] keyWordArray = keyword.split(" ");
//					for(int i=0;i<8;i++)
//					{
//						int no=i+1;
//						request.setAttribute("keyword"+no,keyWordArray[i]);
//					}
//				}
			} catch (Exception e)
			{
				log.error("导航到更新网页异常", e);
			}
		}
	}

	public View save(WebSite website)
	{
		Map<String, Object> map = new HashMap<String, Object>();
		try
		{
			if (website.id != null && website.id > 0)
			{
				website.update();
			} else
			{
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				website.addtime = sdf.format(new Date());
				website.save();
			}
			map.put("stat", "S");
			map.put("msg", "保存成功");
			map.put("id", website.id);
		} catch (Exception e)
		{
			log.error("保存网址失败", e);
			map.put("stat", "E");
			map.put("msg", "保存网址失败");
		}
		return new JsonView(map);
	}

	public View delete()
	{
		Map<String, Object> map = new HashMap<String, Object>();
		try
		{
			String[] ids = request.getParameterValues("ids");
			StringBuffer sql = new StringBuffer("id in (");
			if (ids != null && ids.length > 0)
			{
				for (String id : ids)
				{
					sql.append(id);
					sql.append(",");
				}
			}
			sql.append("EE)");

			int res = WebSite.deleteAll(WebSite.class, sql.toString().replaceAll(",EE", "").replaceAll("EE", ""), null);
			if (res > 0)
			{
				map.put("stat", "S");
				map.put("msg", "删除成功");
			} else
			{
				map.put("stat", "F");
				map.put("msg", "删除失败");
			}
		} catch (Exception e)
		{
			log.error("删除网址异常", e);
			map.put("stat", "E");
			map.put("msg", "删除异常");
		}
		return new JsonView(map);
	}

	/** 分析网站里对应到的url */
	public View fenxi(long id)
	{
		Map<String, Object> map = new HashMap<String, Object>();
		if (id != 0)
		{
			WebSite website = new WebSite();
			try
			{
				website = website.find(website.getClass(), id);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String recordtime = sdf.format(new Date());
				long userid = website.userid;
				AnalysisUrl aurl = new AnalysisUrl();
				List<Map<String, Object>> list = aurl.analysis(website.url, website.keyword);
				int count = 0;
				if (list != null && list.isEmpty() == false)
				{
					for (Map<String, Object> mp : list)
					{
						DownloadUrl durl = new DownloadUrl(userid, id, mp.get("title").toString(), mp.get("href").toString(), Integer.parseInt(mp.get("count").toString()), recordtime);
						try
						{
							//先判断是否已经有了
							List<DownloadUrl> dlist = (List<DownloadUrl>) durl.findBySql(durl.getClass(), 
									"select * from igs_downloadurl where userid=? and websiteid =? and title=? ", 
									new Object[]{ durl.getUserid(), durl.getWebsiteid(), durl.getTitle() });
							//没有则增加
							if(dlist==null || dlist.size()==0)
							{
								durl.save();
								count++;
							}
						} catch (Exception e)
						{
						}
					}
				}
				map.put("stat", "S");
				map.put("msg", "分析完成,符合条件网址为：" + (list != null ? list.size() : 0) + "条,已保存" + count + "条");
				map.put("count", (list != null ? list.size() : 0));
				map.put("data", list);
			} catch (Exception e)
			{
				log.error("分析网址异常", e);
				map.put("stat", "E");
				map.put("msg", "分析网址异常");
			}
		}
		return new JsonView(map);
	}
}
